﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelDemo
{
    class Program
    {
        static object obj = new object();
        static long lvalue = 0;
        static void Main(string[] args)
        {
            //ParallelFor parallelFor = new ParallelFor();
            //parallelFor.ParaFor();

            // ParallelFor();

            // Test2();

            Test1();

            Console.Read();
        }

        private static void Test1()
        {
            int[] count = Enumerable.Range(1, 100).ToArray();
            Parallel.For(1, count.Length, indexer => { Console.WriteLine(indexer); });
        }

        private static void Test2()
        {
            //ParallelLoopState op = new ParallelLoopState() { CancellationToken = CancellationToken.None };
            //Parallel.For(1, 2, (indexer, op) => { Console.WriteLine(indexer); });
        }

        private static void Test3()
        {
            //ParallelOptions op = new() { CancellationToken = CancellationToken.None };
            //op.TaskScheduler = TaskScheduler.Default;
            //op.MaxDegreeOfParallelism = 1;
            //Parallel.For(1, 2, op, indexer => { Console.WriteLine(indexer); });
        }

        private void Test5()
        {
            string[] data = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
            ParallelOptions op = new ParallelOptions();
            op.TaskScheduler = TaskScheduler.Default;//默认的任务调度器
            op.MaxDegreeOfParallelism = 5;//并行度
            op.CancellationToken = CancellationToken.None;//禁止取消
                                                          //自行推断TSource,TLocal
            Parallel.ForEach(data, op,
                () => "开始输出：",//初始化线程本地变量


                (item, loopstate, index, TLocal) =>
                {
                    if (item == "zero")
                    {

                        loopstate.Break();
                        Console.WriteLine($"item:{item} index:{TLocal} ShouldExitCurrentIteration：{loopstate.ShouldExitCurrentIteration} LowestBreakIteration:{loopstate.LowestBreakIteration}");
                        return TLocal + "=>Break";
                    }
                    Console.WriteLine($"item:{item} index:{TLocal}");
                    return TLocal + "=>complete";
                },
               local => Console.WriteLine(local) //输出线程本地变量

            );
        }


        private void Test6()
        {
            string[] data = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };

            //自行推断TSource,TLocal
            Parallel.ForEach(data,
                () => "开始输出：",//初始化线程本地变量
                (item, loopstate, TLocal) =>
                {
                    if (item == "zero")
                    {

                        loopstate.Break();
                        Console.WriteLine($"item:{item} index:{TLocal} ShouldExitCurrentIteration：{loopstate.ShouldExitCurrentIteration} LowestBreakIteration:{loopstate.LowestBreakIteration}");
                        return TLocal + "=>Break";
                    }
                    Console.WriteLine($"item:{item} index:{TLocal}");
                    return TLocal + "=>complete";
                },
               local => Console.WriteLine(local) //输出线程本地变量

            );


        }

        private void Test7()
        {
            string[] data = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };

            //自行推断TSource,TLocal
            Parallel.ForEach(data,
                () => "开始输出：",//初始化线程本地变量
                (item, loopstate, TLocal, index) =>
        {
            if (item == "zero")
            {

                loopstate.Break();
                Console.WriteLine($"item:{item} index:{TLocal} ShouldExitCurrentIteration：{loopstate.ShouldExitCurrentIteration} LowestBreakIteration:{loopstate.LowestBreakIteration}");
                return TLocal + "=>Break";
            }
            Console.WriteLine($"item:{item} index:{TLocal}");
            return TLocal + "=>complete";
        },
           local => Console.WriteLine(local) //输出线程本地变量
        );
        }

        public static void Log(string prefix)
        {
            WriteLine($"{prefix}, task: {Task.CurrentId}, " + $"thread: {Thread.CurrentThread.ManagedThreadId}");
        }

        private static void WriteLine(string msg)
        {
            Console.WriteLine(msg);

        }

        public static void ParallelFor()
        {
            ParallelLoopResult result = Parallel.For(0, 10, i =>
            {
                Log($"S {i}");
                Task.Delay(10).Wait();
                Log($"E {i}");
            });
            //会等待并行任务完全结束才会继续程序流
            WriteLine($"Is completed: {result.IsCompleted}");
        }

        public static void StopParallelForEarly()
        {
            ParallelLoopResult result =
                Parallel.For(10, 30, (int i, ParallelLoopState pls) =>
                {
                    Log($"S {i}");
                    if (i > 15)
                    {
                        pls.Break();
                        Log($"Break out... {i}");
                    }
                    Task.Delay(10).Wait();
                    Log($"E {i}");
                });
            WriteLine($"Is completed: {result.IsCompleted}");
            WriteLine($"lowest break iteration: {result.LowestBreakIteration}");
        }


        private static void Test22()
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

            Console.ForegroundColor = ConsoleColor.Red;
            stopwatch = new System.Diagnostics.Stopwatch();
            Console.ForegroundColor = ConsoleColor.Red;
            stopwatch.Start();

            int temp = int.MaxValue / 100;

            //第一层循环10次
            for (int j = 0; j < 10; j++)
            {
                //第二层循环temp次
                for (int i = 0; i < temp; i++)
                {
                    //本来是不需要加的，为了控制单一变量，使其和并行一致
                    lock (obj)
                    {
                        lvalue += i;
                    }
                }
            }
            Console.WriteLine("串行总用   " + stopwatch.ElapsedMilliseconds + "ms lvalue=" + lvalue);

            lvalue = 0;
            stopwatch = new System.Diagnostics.Stopwatch();
            Console.ForegroundColor = ConsoleColor.Green;
            stopwatch.Start();
            //第一层循环10次
            Parallel.For(0, 10, item =>
            {
                //第二层循环temp次
                for (int i = 0; i < temp; i++)
                {
                    lock (obj)
                    {
                        lvalue += i;
                    }
                }
            });
            Console.WriteLine("并行总用   " + stopwatch.ElapsedMilliseconds + "ms lvalue=" + lvalue);
        }

        private static void Test00()
        {
            double value1 = double.MinValue;
            var sss = value1.ToString();

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

            Console.ForegroundColor = ConsoleColor.Red;
            stopwatch = new System.Diagnostics.Stopwatch();
            Console.ForegroundColor = ConsoleColor.Red;
            stopwatch.Start();
            int temp = int.MaxValue / 100;
            for (int j = 0; j < 10; j++)
            {
                string value = "";
                for (int i = 0; i < temp; i++)
                {
                    value = i.ToString();
                }
            }
            Console.WriteLine("串行总用   " + stopwatch.ElapsedMilliseconds + "ms");

            stopwatch = new System.Diagnostics.Stopwatch();
            Console.ForegroundColor = ConsoleColor.Green;
            stopwatch.Start();
            Parallel.For(0, 10, item =>
            {
                string value = "";
                for (int i = 0; i < temp; i++)
                {
                    value = i.ToString();
                }
            });
            Console.WriteLine("并行总用   " + stopwatch.ElapsedMilliseconds + "ms");
        }

        private static void Test10()
        {
            CancellationTokenSource cancellationSource = new CancellationTokenSource();
            ParallelOptions options = new ParallelOptions();
            options.MaxDegreeOfParallelism = 2; // 最大并行度，并行的任务有几个
            options.CancellationToken = cancellationSource.Token;

            //直接循环100次(0开始100结束)，并输出线程id和循环到了几次
            Parallel.For(0, 100, (i) =>
            {
                Console.WriteLine("Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
            });

            //这是一个跳出循环的实例
            //在 Parallel.For中，不能使用与顺序循环中相同的 break 或 Exit 语句，这是因为这些语言构造对于循环是有效的，而并行“循环”实际上是方法，不是循环。 相反，可以使用 Stop 或 Break 方法
            //1.Stop 调用方法指示尚未开始的循环的任何迭代都无需运行。 它可以有效地取消循环的任何其他迭代。 但是, 它不会停止已经开始执行的任何迭代。调用方法会导致此IsStopped属性返回true到仍在执行的循环的任何迭代。 Stop 这对于长时间运行的迭代特别有用, 它可以检查IsStopped属性并在其值为时true提前退出。
            //2.Break 指示应运行当前迭代之后的任何迭代。 它可以有效地取消循环的任何其他迭代。 但是, 它不会停止已经开始执行的任何迭代。 例如, 如果Break是从从0到1000的并行循环的第100迭代调用的, 则所有小于100的迭代仍应运行, 但不会执行从101到1000的迭代。
            //Stop和Break的区别就在于，Stop仅仅通知其他迭代尽快结束，而Break不仅通知其他迭代尽快结束，同时还要保证退出之前要完成LowestBreakIteration之前的迭代。
            ParallelLoopResult loopResult = Parallel.For(0, 1000, options, (i, loopState) =>
            {
                if (i == 100)
                {
                    loopState.Stop();
                    Console.WriteLine("Stop Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
                }

                Console.WriteLine("Finish Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
            });


            //最大并行度，并行的任务有几个，这是在上面设置的2个
            Parallel.For(0, 10, options, (i) =>
            {
                Console.WriteLine("Thread={0}, i={1}", Thread.CurrentThread.ManagedThreadId, i);
            });

            Parallel.For(0, 10, options, (i, localState) =>
            {
                Console.WriteLine("i={0}, Task={1}, Thread={2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
            });

        }
    }
}
